import React, { useEffect } from "react";
import "./HeroDetail.css";
import axios from "axios";
import { useState } from "react";
// 1. 导入
import { useParams } from "react-router-dom"; // params 形式处理
import { useSearchParams } from "react-router-dom"; // query 形式处理
import { useLocation } from "react-router-dom"; // state 形式处理
import { useNavigate } from "react-router-dom";

export default function HeroDetail() {
  //声明状态 控制英雄的数据
  let [hero, setHero] = useState({});
  //2. 调用函数 获得参数
  // let params = useParams(); //params 形式处理
  // let [searchParams] = useSearchParams();// query 形式处理
  let location = useLocation(); // state 形式处理
  let navigate = useNavigate();

  //动态的展示某个英雄的数据
  useEffect(() => {
    //3. 获取 id 参数
    // let {id} = params;
    // let id = searchParams.get('id');
    let { id } = location.state;

    async function getHeroInfo() {
      //发送请求
      let result = await axios.get(`http://api.xiaohigh.com/heros/${id}`);
      //渲染英雄的数据
      setHero(result.data);
    }

    getHeroInfo();
  }, []);

  //声明函数 返回
  let back = () => {
    //返回  history.go(-2)
    navigate(-1);
  };

  // console.log(hero.skills.map); // hero.skills undefined
  // console.log(hero?.skills.map); // hero.skills undefined
  // console.log(hero.skills?.map); // hero.skills undefined
  return (
    <div className="detail-root">
      <div className="container herodetail-container">
        {/* 左侧部分 */}

        <div className="left col-xs-3" style={{ paddingTop: "20px" }}>
          <button className="btn btn-primary" onClick={back}>
            返回
          </button>
          <h3>{hero.name}</h3>
          <p className="type">类型: {hero.type}</p>
          <div className="skill">
            <div className="row">
              {hero.skills?.map((item, index) => {
                return (
                  <div className="col-xs-3" key={index}>
                    <img
                      width="100%"
                      src={`http://cdn.xiaohigh.com${item.img}`}
                      alt=""
                    />
                    <p className="skill">{item.name}</p>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* 右侧部分 */}
        <div className="right col-xs-9">
          <div>
            {/* 英雄大图 */}
            <img
              width="100%"
              src={
                hero.big_image ? `http://cdn.xiaohigh.com${hero.big_image}` : ""
              }
              alt=""
            />
            <hr />
            <p dangerouslySetInnerHTML={{ __html: hero.intro }}></p>
          </div>
        </div>
      </div>
    </div>
  );
}
